package com.example.forumsystem.controller;

import com.example.forumsystem.common.AppResult;
import com.example.forumsystem.common.ResultCode;
import com.example.forumsystem.model.User;
import com.example.forumsystem.services.IUserService;
import com.example.forumsystem.utils.MD5Utils;
import com.example.forumsystem.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

//对controller进行说明
@Api(tags = "用户接口")
//日志注解
@Slf4j
//返回数据控制器
@RestController
//路由映射 一级路径
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @ApiOperation("用户注册")
    @PostMapping("/register")
    //用户名 昵称 密码 重复密码
    public AppResult register (@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                               @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                               @ApiParam("密码") @RequestParam("password") @NonNull String password,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        // 校验参数的有效性
       /* if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)
                || StringUtils.isEmpty(nickname)){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/
        //校验两次密码是否一致
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成salt
        String salt = UUIDUtils.UUID_32();
        //生成密码的密文
        String encryptPssword = MD5Utils.md5Salt(password, salt);
        //设置密码和盐
        user.setPassword(encryptPssword);
        user.setSalt(salt);

        //调用Service方法
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }
}
